package JdbcTemplate;

import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class JdbcTemplateDemo {
    @Test
    public void test(){
        //1创建jdbcTemplate对象
        //参数介绍连接池
        //jdbctemplate内部封装了连接池 我们只需要给他提供连接池即可
//从连接池中获取连接和归还连接
        JdbcTemplate Template = new JdbcTemplate(JdbcUtils.getDataSource());
        //编写sql语句建表语句
        String sql="CREATE TABLE teacher(id INT PRIMARY KEY AUTO_INCREMENT ,NAME VARCHAR(20),sex VARCHAR (10));";
        Template.execute(sql);

            }
            @Test//增加
    public void insert(){
                JdbcTemplate Template = new JdbcTemplate(JdbcUtils.getDataSource());
        //编写sql语句
                String sql="insert into teacher values(?,?,?)";
                //执行sql
                Template.update(sql,null,"张三","男");
            }
            @Test
    public void select(){
        //创建jdbcTempalet对象
                JdbcTemplate Template = new JdbcTemplate(JdbcUtils.getDataSource());
                //编写sql语句
                String sql="select name from teacher";
                //执行sql语句
                String s = Template.queryForObject(sql, String.class);
                System.out.println(s);

            }
            @Test
    public void select1(){
                JdbcTemplate Template = new JdbcTemplate(JdbcUtils.getDataSource());
               //编写sql语句
                String sql="select * from teacher where id=?";
               //将查询到的结果封装成map集合
                Map<String, Object> stringObjectMap = Template.queryForMap(sql, 1);
                //根据键取值
                Set<String> set = stringObjectMap.keySet();
               //增加for循环遍历set
                for (String s : set) {
                    Object o = stringObjectMap.get(s);
                    System.out.println(s+">"+o);
                }
            }
            @Test
    public void list(){
                JdbcTemplate t = new JdbcTemplate(JdbcUtils.getDataSource());
                List<Map<String, Object>> list = t.queryForList("select * from teacher");
                //遍历集合
                list.forEach(System.out::println);
            }

}
